﻿@using Signum.Web.Properties
@using Signum.Entities.DynamicQuery
@using Signum.Engine.DynamicQuery
@using System.Configuration
@using Signum.Entities.Reflection
@using Signum.Web.Properties
@model Context
@{ 
    Model.ReadOnly = false; /*SearchControls Context should never inherit Readonly property of parent context */
    FindOptions findOptions = (FindOptions)ViewData[ViewDataKeys.FindOptions];
    QueryDescription queryDescription = (QueryDescription)ViewData[ViewDataKeys.QueryDescription];
    var entityColumn = queryDescription.Columns.SingleEx(a => a.IsEntity);
    Type entitiesType = Lite.Extract(entityColumn.Type);
    Implementations implementations = entityColumn.Implementations;
    bool viewable = findOptions.View && (implementations != null || Navigator.IsViewable(entitiesType, EntitySettingsContext.Admin));
    bool? allowMultiple = findOptions.AllowMultiple;
    if (allowMultiple == null && findOptions.FilterMode != FilterMode.OnlyResults)
    {
        allowMultiple = Navigator.QuerySettings(findOptions.QueryName).AllowMultiple;
    }
}
<div id="@Model.Compose("divSearchControl")" 
     class="sf-search-control" 
     data-prefix="@Model.ControlID" 
     data-quickfilter-url="@Url.SignumAction("QuickFilter")"
     data-search-url="@Url.SignumAction("Search")"
     data-popup-save-url="@Url.SignumAction("TrySavePartial")"
     data-add-filter-url="@Url.Action("AddFilter", "Signum")"
     @(findOptions.EntityContextMenu ? " data-entity-ctx-menu-url=" + Url.SignumAction("GetContextualPanel") : "")
     >

    @Html.Hidden(Model.Compose("sfWebQueryName"), Navigator.ResolveWebQueryName(findOptions.QueryName), new { disabled = "disabled" })
    @Html.Hidden(Model.Compose("sfAllowMultiple"), allowMultiple.ToString(), new { disabled = "disabled" })
    @Html.Hidden(Model.Compose("sfAllowChangeColumns"), findOptions.AllowChangeColumns.ToString(), new { disabled = "disabled" })
    @Html.Hidden(Model.Compose("sfView"), viewable, new { disabled = "disabled" })
    @Html.Hidden(Model.Compose("sfFilterMode"), findOptions.FilterMode.ToString(), new { disabled = "disabled" })
    @Html.Hidden(Model.Compose("sfOrders"), findOptions.OrderOptions.IsEmpty() ? "" :
        (findOptions.OrderOptions.ToString(oo => (oo.OrderType == OrderType.Ascending ? "" : "-") + oo.Token.FullKey(), ";") + ";"))
    @Html.Hidden(Model.Compose("sfEntityTypeNames"), 
        implementations == null ? Navigator.ResolveWebTypeName(entitiesType) :
                                implementations.IsByAll ? "[All]" :
                                ((ImplementedByAttribute)implementations).ImplementedTypes.ToString(t => Navigator.ResolveWebTypeName(t), ","), 
        new { disabled = "disabled" })
    
    @if(findOptions.SearchOnLoad)
    {
        <script type="text/javascript">
            $(document).ready(function () { { SF.FindNavigator.searchOnLoad('@Model.ControlID'); } });
            </script>    
    }
    
    @{
        bool filtersAlwaysHidden = findOptions.FilterMode == FilterMode.AlwaysHidden || findOptions.FilterMode == FilterMode.OnlyResults;
        bool filtersVisible = findOptions.FilterMode == FilterMode.Visible;
     }
    
    <div style="display:@(filtersAlwaysHidden ? "none" : "block")">
        <div class="sf-fields-list">
            <div class="ui-widget sf-filters" @(filtersVisible ? "" : "style=display:none")>
                <div class="ui-widget-header ui-corner-top sf-filters-body">
                    @Html.TokenOptionsCombo(queryDescription.QueryName, SearchControlHelper.RootTokensCombo(queryDescription, null), Model, 0, false)
                
                    @Html.Href(
                            Model.Compose("btnAddFilter"), 
                            Resources.FilterBuilder_AddFilter, 
                            "",
                            Resources.Signum_selectToken,
                            "sf-query-button sf-add-filter sf-disabled", 
                            new Dictionary<string, object> 
                            { 
                                { "data-icon", "ui-icon-arrowthick-1-s" },
                                { "data-url", Url.SignumAction("AddFilter") }
                            })

                    @if (string.IsNullOrEmpty(Model.ControlID) && findOptions.AllowChangeColumns)
                    {
                        @Html.Href(
                            Model.Compose("btnAddColumn"), 
                            Resources.FilterBuilder_AddColumn, 
                            "",
                            Resources.Signum_selectToken,
                            "sf-query-button sf-add-column sf-disabled", 
                            new Dictionary<string, object> 
                            { 
                                { "data-icon", "ui-icon-arrowthick-1-e" },
                                { "data-url", Url.SignumAction("GetColumnName") }
                            })
                    }
                </div>
                @{ 
                    ViewData[ViewDataKeys.FilterOptions] = findOptions.FilterOptions;
                    Html.RenderPartial(Navigator.Manager.FilterBuilderView); 
                }
            </div>
        </div>
    </div>
    
    @if (!filtersAlwaysHidden)
    {
        @Html.Href("",
                (filtersVisible ? Resources.Signum_hideFilters : Resources.Signum_showFilters),
                "",
                (filtersVisible ? Resources.Signum_hideFilters : Resources.Signum_showFilters),
                "sf-query-button" + " sf-filters-header" + (filtersVisible ? "" : " close"),
                new Dictionary<string, object> 
                { 
                    { "onclick", "new SF.FindNavigator({{prefix: '{0}'}}).toggleFilters(this)".Formato(Model.ControlID) },
                    { "data-icon", filtersVisible ? "ui-icon-triangle-1-n" : "ui-icon-triangle-1-e" }
                })
    }
    
    <div class="sf-query-button-bar" style="display:@((findOptions.FilterMode != FilterMode.OnlyResults) ? "block" : "none")">
        <button type="submit" class="sf-query-button sf-search" data-icon="ui-icon-search" id="@Model.Compose("qbSearch")" onclick="@("new SF.FindNavigator({{prefix:'{0}',searchControllerUrl:'{1}'}}).search();return false;".Formato(Model.ControlID, Url.SignumAction("Search")))">@Resources.Search</button>
        @if (findOptions.Create && (implementations != null || Navigator.IsCreable(entitiesType, EntitySettingsContext.Admin)) && viewable)
        {
            bool hasManyImplementations = implementations != null && !implementations.IsByAll && ((ImplementedByAttribute)implementations).ImplementedTypes.Length > 1;
            string creating = findOptions.Creating.HasText() ? findOptions.Creating :
                "SF.FindNavigator.create({{prefix:'{0}',controllerUrl:'{1}'}},'{2}');return false;".Formato(
                    Model.ControlID, 
                    Url.SignumAction(string.IsNullOrEmpty(Model.ControlID) ? "Create" : "PopupCreate"),
                    hasManyImplementations ? RouteHelper.New().SignumAction("GetTypeChooser") : "");
            <a class="sf-query-button" data-icon="ui-icon-plusthick" data-text="false" id="@Model.Compose("qbSearchCreate")" onclick="@creating">@Resources.Search_Create</a>
        }
        @ButtonBarQueryHelper.GetButtonBarElementsForQuery(new QueryButtonContext
        {
            ControllerContext = this.ViewContext,
            QueryName = findOptions.QueryName,
            ManualQueryButtons = (ToolBarButton[])ViewData[ViewDataKeys.ManualToolbarButtons],
            EntityType = entitiesType,
            Prefix = Model.ControlID
        }).ToString(Html)
    </div>
    @if (findOptions.FilterMode != FilterMode.OnlyResults)
    {
        <div class="clearall">
        </div>
    }
    <div id="@Model.Compose("divResults")" class="ui-widget ui-corner-all sf-search-results-container">
        <table id="@Model.Compose("tblResults")" class="sf-search-results">
            <thead class="ui-widget-header ui-corner-top">
                <tr>
                    @if (allowMultiple.HasValue)
                    {
                        <th class="ui-state-default th-col-selection">
                            @if (allowMultiple.Value)
                            {
                                @Html.CheckBox(Model.Compose("cbSelectAll"), false, new { onclick = "javascript:new SF.FindNavigator({{prefix:'{0}'}}).toggleSelectAll();".Formato(Model.ControlID) })
                            }
                        </th>
                    }
                    @if (viewable)
                    {
                        <th class="ui-state-default th-col-entity">
                        </th>
                    }
                    @{List<Column> columns = findOptions.MergeColumns(); }
                    @foreach (var col in columns)
                    {
                        var order = findOptions.OrderOptions.FirstOrDefault(oo => oo.Token.FullKey() == col.Name);
                        OrderType? orderType = null;
                        if (order != null)
                        {
                            orderType = order.OrderType;
                        }
                        <th class="ui-state-default @((orderType == null) ? "" : (orderType == OrderType.Ascending ? "sf-header-sort-down" : "sf-header-sort-up"))">
                            <input type="hidden" value="@col.Name" />
                            @col.DisplayName
                        </th>
                    }
                </tr>
            </thead>
            <tbody class="ui-widget-content">
                @{ int columnsCount = columns.Count + (viewable ? 1 : 0) + (allowMultiple.HasValue ? 1 : 0); }
                <tr>
                    <td colspan="@columnsCount">@Resources.Signum_noResults</td>
                </tr>
                @{ 
                    ViewData[ViewDataKeys.ElementsPerPage] = findOptions.ElementsPerPage ?? (Navigator.Manager.QuerySettings.GetOrThrow(findOptions.QueryName, "Missing QuerySettings for QueryName {0}").ElementsPerPage) ?? FindOptions.DefaultElementsPerPage;
                    ViewData[ViewDataKeys.FilterMode] = findOptions.FilterMode;
                    ViewData[ViewDataKeys.SearchControlColumnsCount] = columnsCount;
                }
                @Html.Partial(Navigator.Manager.PaginationView, Model)
            </tbody>
        </table>
    </div>
</div>
<script type="text/javascript">
    new SF.FindNavigator({ prefix: "@Model.ControlID" }).initialize();
</script>
